package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 林道样
 * @date 2020-03-08 15:04
 */
@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionDao permissionDao;

    //新增权限
    public void add(Permission permission) {
        permissionDao.add(permission);
    }
    //分页查询所有
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Permission> page = permissionDao.findPage(queryString);
        List<Permission> result = page.getResult();
        long total = page.getTotal();
        return new PageResult(total, result);
    }
    //根据id查询权限  用于编辑时的数据回显
    public Permission findById(Integer id) {
        return permissionDao.findById(id);
    }
    //编辑权限
    public void edit(Permission permission) {
        permissionDao.edit(permission);
    }
    //删除对应id的权限
    public void delete(Integer id) {
        //根据权限id  查询权限和角色的关系表
        Long count = permissionDao.selectCountByPermissionId(id);
        //判断该权限是否已经赋予了角色
        if (count>0){
            //已经被赋予角色  不可被删除
            throw new RuntimeException(MessageConstant.DELETE_PERMISSION_FAIL);
        }
        //如果没有赋予角色  则可以删除
        permissionDao.delete(id);

    }
}
